package com.ahdms.es.util;

import com.ahdms.es.config.PropertiesConfig;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.stream.Stream;

/**
 * @author qinxiang
 * @date 2021-04-09 14:24
 */
public class PropertiesUtils {

    public static void convert(Properties properties) throws Exception {
        convert(properties,PropertiesConfig.class);
    }

    public static <T> T convert(Properties properties, Class<T> beanType) throws Exception {
        T t = beanType.newInstance();
        Stream.of(beanType.getFields()).forEach(field -> {
            String name = field.getName();
            if (properties.containsKey(name)) {
                Class<?> type = field.getType();
                try {
                    Method method = beanType.getMethod("set" + StringUtils.upperStart(name), type);
                    if (type.equals(Boolean.class)) {
                        method.invoke(t, Boolean.valueOf(properties.getProperty(name)));
                    } else {
                        method.invoke(t, properties.getProperty(name));
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        });

        return t;
    }


}
